package model;

import java.io.IOException;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Iterator;

public class GameSocketThread extends Thread
{

	private ArrayList<Thread> allPlayersSockets;
	private ArrayList<Integer> playerCommands;
	private ArrayList<GameTile> gameTiles;

	private GameQueue gameQueue;

	public GameSocketThread(ArrayList<Thread> allPlayersSockets,
			ArrayList<Integer> playerCommands, ArrayList<GameTile> gameTiles, GameQueue gameQueue)
	{
		this.allPlayersSockets = allPlayersSockets;
		this.playerCommands = playerCommands;
		this.gameTiles = gameTiles;
		this.gameQueue = gameQueue;
	}

	public void run()
	{

		for (int i = 0; i < 4; i++)
		{
			playerCommands.add(null);
		}
		System.out.println("Running GameSocketThread");
		while (true)
		{
			synchronized (allPlayersSockets)
			{
				/*
				try {
					for(Thread t: allPlayersSockets){

						if(t.getState() == State.WAITING){
							System.out.println(t.getName()+ " is waiting");
							sleep(2000);
							if(gameQueue.getNumPlayers() == 2){
								System.out.println("NOTIFY");
								allPlayersSockets.notifyAll();
							}
						} 
						
					}
				}	catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
			}
		}
	}

	/**
	 * Sends and recieves a heartbeat to ensure that the client is still
	 * connected
	 * 
	 * @throws IOException
	 */

	/**  @author Gareth - To Ian
	 * 	- I changed this method to return an int instead of a string
	 *  - For some reason, removing the 2nd if statement will cause the 
	 *    server to thinkthat the client is returning 2 0's and their number
	 *    Made small switch statement to handle case 5: create new game
	 *    and to return true for now (instead of 1 and 0's, im returning
	 *    boolean true or false for the time being)
	 */

	public boolean heartbeat(GameSocket gameSocket) throws IOException
	{

		gameSocket.getOut().write("");
		return false;

	}

	public ArrayList<Thread> getAllPlayersSockets()
	{
		return allPlayersSockets;
	}

	public void setAllPlayersSockets(ArrayList<Thread> allPlayersSockets)
	{
		this.allPlayersSockets = allPlayersSockets;
	}

	public ArrayList<GameTile> getAllTiles(){
		return gameTiles;
	}

	public GameTile getGameTile(int xCoord, int yCoord){
		for(GameTile gT:gameTiles){
			if (gT.getxCoord() == xCoord && gT.getyCoord() == yCoord){
				return gT;
			}
		}
		return null;
	}


}